package com.stationbuilding.fragment.safe;

import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.Toast;
import com.stationbuilding.R;
import com.stationbuilding.adapter.TimeSpinnerAdapter;
import com.stationbuilding.api.RetrofitManager;
import com.stationbuilding.bean.DictBean;
import com.stationbuilding.bean.DictListBean;
import com.stationbuilding.bean.ScoreListBean;
import com.stationbuilding.constants.Constants;
import com.stationbuilding.utils.PreferenceHelper;
import java.util.ArrayList;
import java.util.List;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import lecho.lib.hellocharts.formatter.ColumnChartValueFormatter;
import lecho.lib.hellocharts.formatter.SimpleColumnChartValueFormatter;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Column;
import lecho.lib.hellocharts.model.ColumnChartData;
import lecho.lib.hellocharts.model.SubcolumnValue;
import lecho.lib.hellocharts.util.ChartUtils;
import lecho.lib.hellocharts.view.ColumnChartView;

public class SafeFragmentScore extends Fragment {

    private View view;
    private Spinner spinner;
    private TimeSpinnerAdapter spinnerAdapter;
    private String timeId;
    private List<DictBean> timeList = new ArrayList<>();
    private ProgressDialog dialog;//加载提示
    private ColumnChartView columnChart;
    private String token = PreferenceHelper.getInstance(getActivity()).getToken();
    private Spinner.OnItemSelectedListener spinnerItemSelectedListener = new Spinner.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            timeId = timeList.get(position).getId();
            setColumnChartData();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_safe_score, container, false);
        init();
        return view;
    }

    private void init() {
        spinner = (Spinner) view.findViewById(R.id.time_spinner);
        spinnerAdapter = new TimeSpinnerAdapter(getActivity(), R.layout.statistic_spinner_item, timeList);
        spinnerAdapter.setDropDownResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(spinnerAdapter);
        spinner.setOnItemSelectedListener(spinnerItemSelectedListener);
        loadTimeList();

        // 图表
        columnChart = (ColumnChartView) view.findViewById(R.id.chart);
    }
    /**
     * 数据加载
     */
    private void loadTimeList() {
        RetrofitManager.toSubscribe(
                RetrofitManager.getApiService().getDictListByPid(token, Constants.DICT_ID_STATISTIC_DATE),
                new Observer<DictListBean>() {

                    @Override
                    public void onComplete() {
                        spinner.setSelection(0);
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }
                        Toast.makeText(getActivity(), "网络连接失败，请重新加载", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        if (dialog == null || !dialog.isShowing()) {
                            dialog = ProgressDialog.show(getActivity(), null, "加载数据...");
                        }
                    }

                    @Override
                    public void onNext(DictListBean dictListBean) {
                        timeList = dictListBean.getDictList();
                        spinnerAdapter.setTimeList(timeList);
                        spinnerAdapter.notifyDataSetChanged();
                    }
        });
    }

    /**
     * 设置图标数据
     */
    private void setColumnChartData() {
        RetrofitManager.toSubscribe(
                RetrofitManager.getApiService().getScore(token, Constants.QUESTION_TYPE_SAFE, timeId),
                new Observer<ScoreListBean>() {

                    @Override
                    public void onComplete() {
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        if (dialog.isShowing()) {
                            dialog.dismiss();
                        }
                        Toast.makeText(getActivity(), "出错", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        if (dialog == null || !dialog.isShowing()) {
                            dialog = ProgressDialog.show(getActivity(), null, "加载数据...");
                        }
                    }

                    @Override
                    public void onNext(ScoreListBean scoreListBean) {
                        List<Column> columns = new ArrayList<>();
                        ArrayList<AxisValue> axisValuesX = new ArrayList<>();
                        List<SubcolumnValue> values;
                        List<Float> scoreList = scoreListBean.getResultList();
                        List<String> dateList = scoreListBean.getDateList();
                        if (scoreList == null || scoreList.size() == 0) {
                            return;
                        }
                        for (int i = 0; i < scoreList.size(); i++) {
                            values = new ArrayList<>();
                            values.add(new SubcolumnValue(scoreList.get(i), ChartUtils.pickColor()));
                            Column column = new Column(values);
                            column.setHasLabels(true);
                            column.setHasLabelsOnlyForSelected(false);
                            ColumnChartValueFormatter chartValueFormatter = new SimpleColumnChartValueFormatter(2);
                            column.setFormatter(chartValueFormatter);
                            columns.add(column);
                            axisValuesX.add(new AxisValue(i).setLabel(
                                    dateList.get(i).substring(5, 10).replaceAll("-", "/") + "-" + dateList.get(i).substring(17, 22).replaceAll("-", "/")));
                        }

                        ColumnChartData data = new ColumnChartData(columns);

                        Axis axisX = new Axis(axisValuesX);
                        Axis axisY = new Axis().setHasLines(true);
                        axisY.setName("分数");
                        axisX.setTextColor(Color.BLACK);
                        data.setAxisXBottom(axisX);
                        data.setAxisYLeft(axisY);

                        columnChart.setColumnChartData(data);
                    }
        });
    }
}
